const async           = require('async');
const BaseHandler     = require('../base-handler');
const HTTP_VERBS      = require('../../../constants').HTTP_VERBS;

class MarketingProbeHandler extends BaseHandler {

    get pattern() {
        return "/track/:wall_id/:asset_id/:action";
    }

    doGET(request, response) {
        let wallId = request.params.wall_id;
        let assetId = request.params.asset_id;
        let action = request.params.action;
        let data = request.query.data;
        let callback = request.query.callback;

        if ((!request.session.walls[wallId]) || (request.session.walls[wallId] && !request.session.walls[wallId].wall_user_id) || ['like', 'comment', 'conversion'].indexOf(action) < 0) {
            if (callback) {
                return response.end(`${callback}(${JSON.stringify({success: false, error: 'Nothing'})})`);
            } else {
                return response.json({success: false, error: 'Nothing'});
            }
        }

        let wallUserId = request.session.walls[wallId].wall_user_id;

        this.Controller.updateAssetStatistics(assetId, wallUserId, action, data, (result) => {
            if (callback) {
                response.setHeader('Content-Type', 'application/javascript; charset=utf8');
                response.end(`${callback}(${JSON.stringify({success: true, data: result})})`);
            } else {
                response.json({
                    success: true,
                    data: result
                });
            }
        });
    }

    setup() {
        this.registerVerb(HTTP_VERBS.GET, this.doGET);
    }
}

module.exports = MarketingProbeHandler;